package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mars.common.base.UserContextInfo;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.websocket.Message;
import com.mars.framework.websocket.WebSocketServer;
import com.mars.module.admin.entity.SysUserMessageStats;
import com.mars.module.admin.mapper.SysUserMessageStatsMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysMessageRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysMessageMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysMessage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysMessageService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息业务层处理
 *
 * @author mars
 * @date 2023-12-06
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage> implements ISysMessageService {

    private final SysMessageMapper baseMapper;

    private final SysUserMessageStatsMapper sysUserMessageStatsMapper;

    private final WebSocketServer webSocketServer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysMessage add(SysMessageRequest request) {
        SysMessage entity = SysMessage.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        int i = baseMapper.deleteById(id);
        this.updateMsgUnReadNum(1);
        return i > 0;
    }


    /**
     * 更新未读数量
     *
     * @param type 1 1条已读  2 已读所有
     */
    public void updateMsgUnReadNum(Integer type) {
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        SysUserMessageStats messageStats = sysUserMessageStatsMapper.selectOne(Wrappers.lambdaQuery(SysUserMessageStats.class)
                .eq(SysUserMessageStats::getUserId, info.getId()));
        if (type == 1) {
            messageStats.setUnRead(messageStats.getUnRead() - 1);
        } else {
            messageStats.setUnRead(0);
        }
        sysUserMessageStatsMapper.updateById(messageStats);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysMessageRequest request) {
        SysMessage entity = SysMessage.builder().build();
        BeanUtils.copyProperties(request, entity);
        int i = baseMapper.updateById(entity);
        if (request.getStatus() == 1) {
            this.updateMsgUnReadNum(1);
        }
        return i > 0;
    }

    @Override
    public SysMessage getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysMessage> pageList(SysMessageRequest request) {
        Page<SysMessage> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysMessage> query = this.buildWrapper(request);
        IPage<SysMessage> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void readAllMsg() {
        SysMessageRequest request = new SysMessageRequest();
        request.setPageSize(-1);
        request.setStatus(0);
        List<SysMessage> list = this.pageList(request).getList();
        List<SysMessage> messageList = list.stream().peek(x -> x.setStatus(1)).collect(Collectors.toList());
        super.saveOrUpdateBatch(messageList);
        // 修改已读数量
        this.updateMsgUnReadNum(2);
        // 发送消息
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        Message message = Message.builder().receiverId(info.getId())
                .msgNumber(0).content("")
                .senderId(info.getId()).build();
        webSocketServer.sendOneMessage(message);

    }

    private LambdaQueryWrapper<SysMessage> buildWrapper(SysMessageRequest param) {
        LambdaQueryWrapper<SysMessage> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getContent())) {
            query.like(SysMessage::getContent, param.getContent());
        }
        if (StringUtils.isNotBlank(param.getTitle())) {
            query.like(SysMessage::getTitle, param.getTitle());
        }
        if (Objects.nonNull(param.getStatus())) {
            query.eq(SysMessage::getStatus, param.getStatus());
        }
        query.orderByDesc(SysMessage::getCreateTime);
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        query.eq(SysMessage::getReceiver, info.getId());
        return query;
    }

}
